package com.orphan.marketFront.service.impl;

import com.orphan.marketFront.po.Order;
import com.orphan.marketFront.po.OrderDetail;
import com.orphan.marketFront.service.IGoodsSettleService;
import com.orphan.marketFront.service.IOrderService;
import com.orphan.util.dto.OrderDto;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("settleService")
public class IGoodsSettleServiceImpl implements IGoodsSettleService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IOrderService orderService;

    /**
     * 商品结算:接收浏览器支付信息-传递给后端支付，并将订单保存进入数据库
     * @param
     * @return 结算结果
     */
    public boolean goodsSettle(OrderDto orderDto) {
        if(orderDto != null){
            //传递给后端处理扣款
            rabbitTemplate.convertAndSend("SettlementDirectExchange","settlementMessage",orderDto);
            //持久化到数据库
            orderService.insertOrder(orderDto);
            orderService.insertOrderDetail(orderDto);
            return true;
        }
        return false;
    }


    /**
     * 监听支付结果，修改数据库订单支付状态
     * @param map
     */
    @RabbitListener(queues = "settlementBackQueue")
    public void settlementListener(Map map) {
        System.out.println(map);
        String orderId = String.valueOf(map.get("orderId"));
        Integer payStatus = (Integer)map.get("payStatus");
        if(payStatus != 0){
            orderService.updateOrderPayStatus(orderId, payStatus);
        }
    }

    /**
     * 查询数据库中的指定订单支付结果，如果支付成功，回复浏览器，并投递订单给后台
     * @param orderId 订单编号
     * @return
     */
    public Integer checkPayment(String orderId) {
        Order order = orderService.selectOrderById(orderId);
        Integer payStatus = order.getPayStatus();
        List<OrderDetail> orderDetails = orderService.selectOrderDetailByOrderId(orderId);
        if(payStatus != 0){
            OrderDto orderDto = orderService.orderDtoParse(order, orderDetails);
            postOrderMessage(orderDto);
        }
        return payStatus;
    }


    /**
     * 将支付成功的订单传递给后台进一步处理
     * @param  orderDto 订单
     */
    public void postOrderMessage(OrderDto orderDto) {
        rabbitTemplate.convertAndSend("newOrderExchange","newOrderKey",orderDto);
    }

//    @RabbitListener(queues = "newOrderQueue")
//    public void newListener(OrderDto orderDto) {
//        System.out.println(orderDto);
//    }

//    SettlementOrderDto orderDtoParseToSettlementOrderDto(OrderDto orderDto);

}
